import os,tempfile,shutil,commands
import pickle
import sys
import time

inf=open(sys.argv[1],"r")

vmid=pickle.load(inf)
serverstr=pickle.load(inf)
serverhostname=pickle.load(inf)

MetaDataProvided=False

while not MetaDataProvided:
    
    cmdstr="curl -s \"%s/getVMAttr?vmid=%s&name=MetaDataProvided\""%(serverstr,vmid)

    (status,output)=commands.getstatusoutput(cmdstr)

    print "Running command=%s, status=%d, output=%s"%(cmdstr,status,output)
    if output=="True":
        MetaDataProvided=True

    time.sleep(5)
    
#now obtain metadata
cmdstr="curl -s \"%s/getVMAttr?vmid=%s&name=MetaData\""%(serverstr,vmid)
(status,output)=commands.getstatusoutput(cmdstr)
print "Running command=%s, status=%d, output=%s"%(cmdstr,status,output)

#Metadata will be the result from "tar cz certfiles|base64 -w 0"
#save it somewhere


metadata=output

base64file=tempfile.gettempdir()+"metadata.tgz.base64"

ouf=open(base64file,"w")
ouf.write(metadata)
ouf.close()

try:
    os.makedirs("/etc/puppet")
except:
    pass

cmdstr="base64 -d -w 0 %s|tar zx -C /etc/puppet/"%(base64file)
(status,output)=commands.getstatusoutput(cmdstr)
print "Running command=%s, status=%d, output=%s"%(cmdstr,status,output)

#create conf file
cmdstr='puppetd --genconf --server=%s |sed s/"rrdinterval = 1800"/"rrdinterval = 60"/g|sed s/"# runinterval = 1800"/"runinterval = 60"/g|sed s/"splaylimit = 1800"/"splaylimit = 60"/g|sed s/"genconfig = true"/"genconfig = false"/g' % serverhostname
(status,output)=commands.getstatusoutput(cmdstr)
print "Running command=%s, status=%d, output=%s"%(cmdstr,status,output)

ouf=open("/etc/puppet/puppet.conf","w")
ouf.write(output)
ouf.close()

cmdstr='puppetd'
(status,output)=commands.getstatusoutput(cmdstr)
print "Running command=%s, status=%d, output=%s"%(cmdstr,status,output)
